package com.xbongbong.parent.parse.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.UserHelper;
import com.xbongbong.paas.pojo.dto.AnalysisDataDTO;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.parent.abstracts.AbstractFormDataAnalysisDataHelp;
import com.xbongbong.parent.help.AnalysisTemplateFieldHelp;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.domain.entity.PersonLabelEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.label.pojo.LabelForDetailUpadatePojo;
import com.xbongbong.pro.label.pojo.dto.PersonLabelFindDTO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.enums.BusinessFieldEnum;
import com.xbongbong.saas.enums.NumberTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.dictionary.IsRedEnum;
import com.xbongbong.saas.help.FormDataAnalysisHelp;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.PersonLabelModel;
import com.xbongbong.saas.model.ProductCategoryModel;
import com.xbongbong.saas.model.PublicGroupSeniorModel;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.FundSetHelp;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 获取数据详情时解析数据
 * @author: wufeng
 * @date: 2018/12/11 15:17
 * @desrcption:
 */
@Component
public class FormDataGetAnalysisDataHelp extends AbstractFormDataAnalysisDataHelp {

    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private LabelModel labelModel;
    @Resource
    private FormDataAnalysisHelp formDataAnalysisHelp;
    @Resource
    private PersonLabelModel personLabelModel;
    @Resource
    private FundSetHelp fundSetHelp;
    @Resource
    private ProductCategoryModel productCategoryModel;
    @Resource
    private PublicGroupSeniorModel publicGroupSeniorModel;
    @Resource
    private AnalysisTemplateFieldHelp analysisTemplateFieldHelp;

    @Override
    public void analysisData(AnalysisDataDTO analysisDataDTO, JSONObject resultJsonObject, Map<String, Object> linkData
                    ,Set<Object> linkDataSet) throws XbbException {
        // TODO 关于成员和部门回显需要去掉离职人员，现在直接不限，具体如何显示，未解决
        FieldAttrEntity fieldAttrEntity = analysisDataDTO.getFieldAttrEntity();
        String key = analysisDataDTO.getAttr();

        Map<String, UserEntity> userMap = analysisDataDTO.getUserMap();
        Map<String, DepartmentEntity> departmentMap = analysisDataDTO.getDepartmentMap();
        JSONObject objectJsonObject = analysisDataDTO.getDataJsonObject();

        // 百分比数字字段处理
        String saasAttr = fieldAttrEntity.getSaasAttr();
        boolean rateNumFlag = Objects.equals(ContractEnum.GROSS_PROFIT_RATE.getSaasAttr(), saasAttr)
                || Objects.equals(ContractEnum.CASH_PROFIT_RATE.getSaasAttr(), saasAttr)
                || Objects.equals(ContractEnum.PAY_PERCENT.getSaasAttr(), saasAttr)
                || Objects.equals(SalesOpportunityEnum.GROSS_PROFIT_RATE.getSaasAttr(), saasAttr)
                || Objects.equals(QuotationEnum.GROSS_PROFIT_RATE.getSaasAttr(), saasAttr)
                || Objects.equals(PurchaseEnum.RECEINE_PERCENT.getSaasAttr(), saasAttr);
        if (Objects.equals(fieldAttrEntity.getNumberType(), NumberTypeEnum.RATE.getCode())) {
            rateNumFlag = true;
        }
        Integer saasMark = analysisDataDTO.getSaasMark();
        if(FieldTypeEnum.USER.getType().equals(fieldAttrEntity.getFieldType())
                || FieldTypeEnum.SELECT_DEPARTMENT.getType().equals(fieldAttrEntity.getFieldType())
                || FieldTypeEnum.CREATORID.getType().equals(fieldAttrEntity.getFieldType())){
            if(StringUtil.isNotEmpty(objectJsonObject.getString(key))){
                UserEntity userEntity = userMap.get(objectJsonObject.getString(key));
                if (Objects.nonNull(userEntity)) {
                    ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                    BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                    returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                    resultJsonObject.put(key, returnUserAndDepartmentPojo);
                } else if (Objects.equals(objectJsonObject.getString(key), StringConstant.NOT_IN_SYSTEM_ID)) {
                    ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                    returnUserAndDepartmentPojo.setName(objectJsonObject.getString(fieldAttrEntity.getLinkedText())+"(离职)");
                    returnUserAndDepartmentPojo.setId(objectJsonObject.getString(key));
                    resultJsonObject.put(key, returnUserAndDepartmentPojo);
                }
            }
        } else if(Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)
                && FieldTypeEnum.COMBO.getType().equals(fieldAttrEntity.getFieldType())) {
            formDataAnalysisHelp.analysisComboWithColor(objectJsonObject, resultJsonObject,fieldAttrEntity, analysisDataDTO.getCorpid());
        } else if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldAttrEntity.getFieldType())) {
            formDataAnalysisHelp.analysisListStageJsonObjectWithColor(resultJsonObject, analysisDataDTO);
        } else if (Objects.equals(FieldTypeEnum.FIRST_INTO_STAGE_TIME.getType(), fieldAttrEntity.getFieldType())) {
            formDataAnalysisHelp.analysisStageStayTime(resultJsonObject, fieldAttrEntity.getAttr());
        } else if (Objects.equals(FieldTypeEnum.NOW_INTO_STAGE_TIME.getType(), fieldAttrEntity.getFieldType())) {
            formDataAnalysisHelp.analysisStageStayTime(resultJsonObject, fieldAttrEntity.getAttr());
        } else if(FieldTypeEnum.RADIO_GROUP.getType().equals(fieldAttrEntity.getFieldType())) {
            formDataAnalysisHelp.analysisComboWithColor(objectJsonObject, resultJsonObject,fieldAttrEntity, analysisDataDTO.getCorpid());
        } else if(Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark) &&
                (FieldTypeEnum.CHECKBOX_GROUP.getType().equals(fieldAttrEntity.getFieldType())
                || FieldTypeEnum.COMBO_CHECK.getType().equals(fieldAttrEntity.getFieldType()))) {
            // 多选转化成逗号隔开的字符串
            formDataAnalysisHelp.analysisComboWithColor(objectJsonObject, resultJsonObject,fieldAttrEntity, analysisDataDTO.getCorpid());
        } else if (FieldTypeEnum.USER_GROUP.getType().equals(fieldAttrEntity.getFieldType())
                || FieldTypeEnum.OWNERID.getType().equals(fieldAttrEntity.getFieldType())
                || FieldTypeEnum.COUSERID.getType().equals(fieldAttrEntity.getFieldType())) {
            List<UserEntity> userList = UserHelper.getUserByKey(key, objectJsonObject, userMap);
            List<ReturnUserAndDepartmentPojo> resultList = new ArrayList<>();
            userList.forEach(item->{
                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                BeanUtil.copyProperties(item, returnUserAndDepartmentPojo);
                returnUserAndDepartmentPojo.setId(item.getUserId());
                resultList.add(returnUserAndDepartmentPojo);
            });
            resultJsonObject.put(key, resultList);
        } else if(FieldTypeEnum.DEPT.getType().equals(fieldAttrEntity.getFieldType())
                || FieldTypeEnum.DEPARTMENTID.getType().equals(fieldAttrEntity.getFieldType())){
            DepartmentEntity departmentEntity =  departmentMap.get(objectJsonObject.getString(key));
            if(Objects.nonNull(departmentEntity)){
                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                BeanUtil.copyProperties(departmentEntity, returnUserAndDepartmentPojo);
                resultJsonObject.put(key, returnUserAndDepartmentPojo);
            } else {
                resultJsonObject.remove(key);
            }
        } else if (FieldTypeEnum.DEPT_GROUP.getType().equals(fieldAttrEntity.getFieldType())) {
            List<DepartmentEntity> departmentList = UserHelper.getDepartmentByKey(key, objectJsonObject, departmentMap);
            List<ReturnUserAndDepartmentPojo> resultList = new ArrayList<>();
            departmentList.forEach(item->{
                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                BeanUtil.copyProperties(item, returnUserAndDepartmentPojo);
                resultList.add(returnUserAndDepartmentPojo);
            });
            resultJsonObject.put(key, resultList);
        } else if (FieldTypeEnum.LINK_DATA.getType().equals(fieldAttrEntity.getFieldType())
                && Objects.nonNull(objectJsonObject.get(key)) && objectJsonObject.get(key) instanceof Number && !Objects.equals(objectJsonObject.get(key), 0)){
            if (Objects.nonNull(linkData)) {
                linkData.put(key, objectJsonObject.get(key));
            }
            if (Objects.nonNull(linkDataSet)) {
                linkDataSet.add(objectJsonObject.get(key));
            }
            resultJsonObject.put(key, objectJsonObject.get(key));
        } else if (FieldTypeEnum.LINK_DATA_MULTI.getType().equals(fieldAttrEntity.getFieldType())
                && Objects.nonNull(objectJsonObject.get(key))
                && (objectJsonObject.get(key) instanceof JSONArray || objectJsonObject.get(key) instanceof ArrayList || objectJsonObject.get(key) instanceof List)) {
            JSONArray linkDataArray = objectJsonObject.getJSONArray(key);
            if (CollectionsUtil.isNotEmpty(linkDataArray)) {
                if (Objects.nonNull(linkData)) {
                    linkData.put(key, objectJsonObject.get(key));
                }
                if (Objects.nonNull(linkDataSet)) {
                    linkDataSet.addAll(linkDataArray);
                }
                resultJsonObject.put(key, objectJsonObject.get(key));
            }
        } else if (FieldTypeEnum.ADDRESS.getType().equals(fieldAttrEntity.getFieldType())) {
            JSONObject addressJsonObject = objectJsonObject.getJSONObject(key);
            if (Objects.nonNull(addressJsonObject) && Objects.equals(fieldAttrEntity.getShowDetailAddress(), 0)) {
                addressJsonObject.put(BusinessConstant.ADDRESS, "");
            }
            resultJsonObject.put(key, addressJsonObject);
        } else if (FieldTypeEnum.LINK_BUSINESS_SINGLE.getType().equals(fieldAttrEntity.getFieldType())) {
            // saas关联业务的特殊逻辑
            formDataAnalysisHelp.saasAnalysisData(analysisDataDTO, key, objectJsonObject, resultJsonObject);
        } else if(Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.NUM.getType()) && Objects.nonNull(objectJsonObject.get(key))) {
            // 小数精度
            Double value;
            try {
                value = objectJsonObject.getDoubleValue(key);
            } catch (Exception e) {
                value = 0D;
            }
            if(!rateNumFlag) {
                resultJsonObject.put(key, attrDecimalPrecisionHelper.formatPrecisionWithIntegerOnly(value, fieldAttrEntity));
            } else {
                String decValue = attrDecimalPrecisionHelper.setDecPrecision(value * 100, fieldAttrEntity.getAccuracy());
                resultJsonObject.put(key, decValue + "%");
            }

        } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())) {
            resultJsonObject.put(key, formDataAnalysisHelp.analysisAttachmentList(objectJsonObject.getString(key)));
        } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())){
            // 标签解析
            analasisLabel(analysisDataDTO, key, objectJsonObject, resultJsonObject );
        } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.PUBLIC_GROUP.getType()) && Objects.nonNull(objectJsonObject.get(key))){
            dealId2GroupName(analysisDataDTO, key, objectJsonObject, resultJsonObject);
        } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.ACCOUNT_PERIOD.getType())) {
            String receivablePeriod = resultJsonObject.getString(key);
            String returnReceivablePeriod = fundSetHelp.getFormatReceivablePeriod(receivablePeriod);
            resultJsonObject.put(key,returnReceivablePeriod);
        } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.AREA.getType())) {
            analysisArea(analysisDataDTO, resultJsonObject, key, objectJsonObject);
        } else if (Objects.equals(fieldAttrEntity.getSaasAttr(), ContactEnum.PHONE. getSaasAttr())) {
            formDataAnalysisHelp.analysisTelephoneNumber(fieldAttrEntity,objectJsonObject, resultJsonObject, analysisDataDTO.getLoginUser());
        } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.PURCHASEABLE_GOODS.getType())) {
            JSONArray goodsArr = objectJsonObject.getJSONArray(key);
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("idIn", goodsArr);
            params.put(StringConstant.CORPID, analysisDataDTO.getCorpid());
            params.put(StringConstant.DEL, BasicConstant.ZERO);
            List<ProductCategoryEntity> productCategoryEntityList = productCategoryModel.findEntitys(params);
            List<Object> resultList = new ArrayList<>(productCategoryEntityList.size() << 2);
            productCategoryEntityList.forEach(i -> {
                Map<String, Object> resultMap = new HashMap<>(2);
                resultMap.put("id", i.getId());
                resultMap.put("name", i.getName());
                resultList.add(resultMap);
            });
            resultJsonObject.put(key, resultList);
        }else if(Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.TEMPLATE_FIELD.getType())){
            analysisTemplateFieldHelp.analysisTemplateField(analysisDataDTO.getCorpid(),resultJsonObject, fieldAttrEntity.getAttr());
        } else {
            resultJsonObject.put(key, objectJsonObject.get(key));
        }
    }

    /**
     * 处理标签展示
     * @param analysisDataDTO
     * @param key
     * @param objectJsonObject
     * @param resultJsonObject
     */
    private void analasisLabel(AnalysisDataDTO analysisDataDTO, String key, JSONObject objectJsonObject, JSONObject resultJsonObject) {
        JSONArray jsonArray = objectJsonObject.getJSONArray(key);
        if (Objects.isNull(jsonArray)) {
            return;
        }
        List<LabelForDetailUpadatePojo> pojoList = new ArrayList<>();
        List<Long> longs = JSON.parseArray(jsonArray.toJSONString(), Long.class);
        if (!longs.isEmpty()) {
            List<LabelEntity> labelEntities = labelModel.getByLabelIds(longs, analysisDataDTO.getCorpid());
            labelEntities.forEach(item -> {
                LabelForDetailUpadatePojo labelForDetailUpadatePojo= new LabelForDetailUpadatePojo();
                labelForDetailUpadatePojo.setId(item.getId());
                labelForDetailUpadatePojo.setName(item.getName());
                labelForDetailUpadatePojo.setColor(item.getColor());
                labelForDetailUpadatePojo.setTabelType(BasicConstant.ZERO);
                pojoList.add(labelForDetailUpadatePojo);
            });
        }
        PersonLabelFindDTO personLabelFindDTO = new PersonLabelFindDTO(analysisDataDTO.getCorpid(),
                analysisDataDTO.getBusinessType(), analysisDataDTO.getDataId(), analysisDataDTO.getUserId());
        PersonLabelEntity personLabelEntity = personLabelModel.getPersonLabelByRefType(personLabelFindDTO.getCorpid(), personLabelFindDTO.getRefType(), personLabelFindDTO.getRefId(),
                personLabelFindDTO.getOwnerId());
        if (Objects.nonNull(personLabelEntity)) {
            JSONArray labelNameArray = personLabelEntity.getLabelName();
            if (labelNameArray !=null && labelNameArray.size() > 0) {
                for (Object labelName : labelNameArray) {
                    LabelForDetailUpadatePojo labelForDetailUpadatePojo= new LabelForDetailUpadatePojo();
                    labelForDetailUpadatePojo.setId(personLabelEntity.getId());
                    labelForDetailUpadatePojo.setName(labelName.toString());
                    labelForDetailUpadatePojo.setColor(personLabelEntity.getLabelColor());
                    labelForDetailUpadatePojo.setTabelType(BasicConstant.ONE);
                    pojoList.add(labelForDetailUpadatePojo);
                }
            }
        }

        resultJsonObject.put(key, pojoList);
    }

    /**
     * 处理所属分组
     * @param analysisDataDTO
     * @param key
     * @param objectJsonObject
     * @param resultJsonObject
     */
    private void dealId2GroupName(AnalysisDataDTO analysisDataDTO, String key, JSONObject objectJsonObject, JSONObject resultJsonObject) throws XbbException {
        Long groupId = objectJsonObject.getLong(key);
        if (Objects.nonNull(groupId)) {
            PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorModel.getByKey(groupId, analysisDataDTO.getCorpid());
            if (Objects.nonNull(publicGroupSeniorEntity)) {
                resultJsonObject.put(key, publicGroupSeniorEntity.getName());
            }
        }
    }
    /**
     * 红冲合同的计划收款金额、未收金额、坏账金额默认值情况下为0 为了保持和saas以前的一样 这里要改成 --
     * @param formDataGetVO
     */
    public void redPaymentShowHandle(FormDataGetVO formDataGetVO) {
        PaasFormEntity paasFormEntity = formDataGetVO.getPaasFormEntity();
        if(paasFormEntity != null) {
            if (BusinessFieldEnum.PAYMENT.getBusinessType().equals(paasFormEntity.getBusinessType())) {
                JSONObject data = formDataGetVO.getData();
                if (data != null && data.size() > 0) {
                    Double zero = 0D;
                    if (data.containsKey(PaymentEnum.IS_RED.getAttr())) {
                        if (IsRedEnum.RED.getCode().equals(data.getInteger(PaymentEnum.IS_RED.getAttr()))) {
                            if (zero.equals(data.getDouble(PaymentEnum.AMOUNT.getAttr()))) {
                                data.put(PaymentEnum.AMOUNT.getAttr(), BasicConstant.NULL_SHOW_STR);
                            }
                            if (zero.equals(data.getDouble(PaymentEnum.UN_AMOUNT.getAttr()))) {
                                data.put(PaymentEnum.UN_AMOUNT.getAttr(), BasicConstant.NULL_SHOW_STR);
                            }
                            if (zero.equals(data.getDouble(PaymentEnum.BAD_AMOUNT.getAttr()))) {
                                data.put(PaymentEnum.BAD_AMOUNT.getAttr(), BasicConstant.NULL_SHOW_STR);
                            }
                            if (zero.equals(data.getDouble(PaymentEnum.INVOICE_AMOUNT.getAttr()))) {
                                data.put(PaymentEnum.INVOICE_AMOUNT.getAttr(), BasicConstant.NULL_SHOW_STR);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 详情页解析千份位
     * @param formDataGetVO
     * @throws XbbException
     */
    public void analysisGetOfThousandBits(FormDataGetVO formDataGetVO,List<FieldAttrEntity> explainList,Boolean analysisAmountOfThousandBitsWithOriginalValue){
        JSONObject data = formDataGetVO.getData();
        Map<String,Object> explainMap = FormDataAnalysisHelp.needAnalysisFieldAttr(explainList);
        if(data!=null && data.size()>0) {
            Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String attr = entry.getKey();
                formDataAnalysisHelp.analysisAmountOfThousandBitsNomal(data,attr,explainMap,analysisAmountOfThousandBitsWithOriginalValue);
            }
        }
        formDataGetVO.setData(data);
    }

    /**
     * 详情页解析千份位
     * @param data
     * @throws XbbException
     */
    public void analysisGetOfThousandBits(JSONObject data,List<FieldAttrEntity> explainList,Boolean analysisAmountOfThousandBitsWithOriginalValue){
        Map<String,Object> explainMap = FormDataAnalysisHelp.needAnalysisFieldAttr(explainList);
        if(data!=null && data.size()>0) {
            Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String attr = entry.getKey();
                formDataAnalysisHelp.analysisAmountOfThousandBitsNomal(data,attr,explainMap,analysisAmountOfThousandBitsWithOriginalValue);
            }
        }
    }
}
